<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Transaksi
 *
 * @author Hadi
 */
class transaksi_penyewaan extends Admin_My_Controller {

    public function __construct() {
        parent::__construct();

        $this->load->model('transaksi/model_transaksi_penyewaan');
        $this->load->model('transaksi/model_transaksi_penyewaan_invoice');
        $this->load->helper('transaksi_perjanjian');
    }

    /**
     * INVOICE
     */
    public function perjanjian($is_popup) {
        $this->load->library("datagrid");

        $data = array();

        $this->log_event = "Membuka menu data penyewaan";

        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("i.nomor_perjanjian", "c.nama_customer", "v.nama_vessel");
        $field_title = array("Nomor Perjanjian", "To", "Nama Vessel");
        $field_type = array("text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi_penyewaan/perjanjian", $field_name, $field_title, $field_type);
        if ($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(i.tanggal_perjanjian) BETWEEN '" . $data['srcPeriodStart'] . "' AND '" . $data['srcPeriodEnd'] . "' ";
        else
            $where = " WHERE TRUE ";
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $offset = $this->input->get("per_page") ? $this->input->get("per_page") : 0;
        $length = 30;
        $result = $this->model_transaksi_penyewaan->getPerjanjianData($where, $offset, $length);


        if (!$is_popup) {
            $this->datagrid->setActionColumnsWidth(50);
            $this->datagrid->addMenu(GreyBox::createLink(base_url() . "index.php/transaksi_penyewaan/perjanjian_add/", "", "Tambah Data", "add", "onclick", 1024, 600));
            $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi_penyewaan/perjanjian_export/?" . $this->input->server("QUERY_STRING") . "\" class=\"report\" title=\"Export Data Perjanjian\">&nbsp;</a>");
        } else {
            $this->datagrid->setActionColumnVisible(false);
        }



        $rowCount = $result->num_rows();

        $this->datagrid->setColumns("No.", "Nomor Perjanjian", "Tanggal", "To", "Catatan", "Submitter");
        $this->datagrid->setPaginationDataNew($this->model_transaksi_penyewaan->get_scalar("SELECT COUNT(*) as jml FROM data_perjanjian i $where", "jml"), $length, "transaksi_penyewaan/perjanjian", $rowCount, $offset);
        $this->datagrid->setButtonExportVisible(false);

        if ($rowCount > 0) {
            $nomor = $offset + 1;

            foreach ($result->result() as $row) {
                $rowID = $row->id_perjanjian;

                if (!$is_popup) {
                    $this->datagrid->addRowAction("edit('" . $rowID . "')", "edit", "Ubah Invoice");
                    $this->datagrid->addRowAction("cetak('" . $rowID . "')", "resume", "Cetak Perjanjian");
                    $this->datagrid->addRowAction("hapus('" . $rowID . "')", "delete", "Hapus Invoice");
                } else {
                    $this->datagrid->onRowClickAction("parent.parent._obj_fSendValue('" . $rowID . "')");
                }

                $this->datagrid->addRowData(
                        $nomor++, $row->nomor_perjanjian, $row->tanggal_perjanjian, $row->nama_customer, $row->penerbit_perjanjian, $row->submitter
                );
            }
        } else {
            $this->datagrid->setEmptyDataState("Tidak ada data");
        }

        $data['date_picker'] = new jDatePicker();
        $data['filter_panel'] = $filter_panel;
        if (!$is_popup) {
            $data['breadcrumb'] = $this->breadCrumb(true);
            $this->loadMenu('transaksi_penyewaan/perjanjian', $data);
        } else {
            $this->loadMenuHeaderPopup('transaksi_penyewaan/perjanjian', $data);
        }
    }

    public function perjanjian_add($kode = "") {
        $data = array();

        if ($this->input->post("btnSubmit")) {
            $vars = array(
                "nomor_perjanjian" => "",
                "tanggal_perjanjian" => date("Y-m-d"),
                "using_dollar_currency" => "",
                "tambahkan_ppn" => 0,
                "alamat_detail_customer" => "",
                "alamat_komplit" => "",
                "keagenan_kapal" => "",
                "id_vessel" => "",
                "nama_vessel" => "",
                "kontak_komplit" => "",
                "nama_customer" => "",
                "attendance" => "",
                "penerbit_perjanjian" => "",
                "approved_by" => "",
                "diskon" => 0,
                "kesediaan_muat" => "",
                "jenis_muatan" => "",
                "kondisi_kontrak" => "",
                "pelabuhan_muat" => "",
                "pelabuhan_bongkar" => "",
                "jumlah_hari" => "",
                "jumlah_muatan" => "",
                "pengirim_barang" => "",
                "penerima_barang" => "",
                "asuransi_barang" => "",
                "asuransi_kapal" => "",
                "uang_tambang" => "",
                "kondisi_uang_tambang" => "",
                "cara_pembayaran" => "",
                "denda_keterlambatan" => "",
                "remarks" => "",
                "subject" => "",
                "id_bank" => "",
                "id_customer" => "",
                "submitter" => $this->userauth->getNik(),
                "date_submit" => date("Y-m-d H:i:s")
            );
            retrieve_request($data, $vars);
            $data["using_dollar_currency"] = $data["using_dollar_currency"] == "USD" ? 1 : 0;
            if ($data["ppn"] == "on") {
                $data["ppn"] = 1;
            } else {
                $data["ppn"] = 0;
            }

            if (empty($data["id_customer"]))
                $data["id_customer"] = $this->model_transaksi_penyewaan->insertCustomer($data);
            if (empty($data["id_vessel"]))
                $data["id_vessel"] = $this->model_transaksi_penyewaan->insertVessel($data);


            if ($kode == "")
                $id_invoice = $this->model_transaksi_penyewaan->insertUpdatePerjanjian($data);
            else {
                $id_invoice = $kode;
                $this->model_transaksi_penyewaan->insertUpdatePerjanjian($data, $id_invoice);
            }

            $data["is_success"] = 1;
            $data["kode"] = $id_invoice;
        }

        if ($kode != "") {
            retrieve_perjanjian_data($data, $kode);
            foreach($data as $key => $value){
                $data[$key] = str_ireplace("<br>", "\n", $value);
            }
            $data["kode"] = $kode;
        } else {
            $data["tanggal_perjanjian"] = date("Y-m-d");
            $data["penerbit_perjanjian"] = $this->userauth->getNickName();
        }
        $data['gbvessel'] = $this->greybox->createLink(base_url() . 'index.php/popup/vessel', '<span></span>', 'Cari Vessel', 'find', '', 500, 450);
        $data['penerbit_perjanjian'] = $this->userauth->getNickName();
        $data['gbcust'] = $this->greybox->createLink(base_url() . 'index.php/popup/customer', '<span></span>', 'Cari Customer', 'find', '', 750, 450);
        $data['gbbank'] = $this->greybox->createLink(base_url() . 'index.php/popup/bank', '<span></span>', 'Cari Bank', 'find', '', 750, 450);
        $data["prefix"] = $this->model_transaksi_penyewaan->getPrefixPerjanjianNo();
        $this->loadMenuHeaderPopup("transaksi_penyewaan/perjanjian_add", $data);
    }

    public function perjanjian_delete($kode) {
        $this->model_transaksi_penyewaan->deletePerjanjian($kode);
        echo "<script>alert('Data berhasil dihapus');</script>";
        echo "<script>location.href = '" . site_url("transaksi_penyewaan/perjanjian?" . $_SERVER["QUERY_STRING"]) . "'</script>";
    }

    public function perjanjian_print($kode, $page_numer = "") {
        $data["kode"] = $kode;
        if ($page_numer != "") {
            $this->voyage_charter_hal1($kode, $page_numer);
        } else {
            $this->loadMenuHeaderPopup('transaksi_penyewaan/perjanjian_list', $data);
        }
    }

    public function voyage_charter_hal1($kode, $page_number) {
        $data = array();
        retrieve_perjanjian_data($data, $kode);

        $this->load->library("dcpdf");

        $obj_pdf = new dcpdf('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $obj_pdf->SetCreator(PDF_CREATOR);
        $title = "";
        $obj_pdf->SetTitle($title);
        if ($data["use_header"]) {
            $obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
            $obj_pdf->setFooterVisible(TRUE);
        }
        $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $obj_pdf->SetDefaultMonospacedFont('helvetica');
        $obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $obj_pdf->SetFont('times', '', 10);
        $obj_pdf->setFontSubsetting(false);
        $obj_pdf->AddPage();
        $content = $this->load->view("transaksi_penyewaan/perjanjian_voyage" . $page_number, $data, true);
        $obj_pdf->writeHTML($content, true, false, true, false, '');
        $obj_pdf->Output('perjanjian' . $page_numer . '-' . $kode . '.pdf', 'I');
    }

    public function perjanjian_export() {
        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("i.nomor_perjanjian", "c.nama_customer", "v.nama_vessel");
        $field_title = array("Nomor Invoice", "To", "Nama Vessel");
        $field_type = array("text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi_penyewaan/perjanjian", $field_name, $field_title, $field_type);
        if ($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(i.tanggal_perjanjian) BETWEEN '" . $data['srcPeriodStart'] . "' AND '" . $data['srcPeriodEnd'] . "' ";
        else
            $where = " WHERE TRUE ";
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $queryExport = "SELECT i.*, c.*, b.nama_bank, b.nomor_rekening, b.cabang, v.nama_vessel,v.keterangan_vessel
                FROM data_perjanjian i                
                LEFT JOIN master_customer c ON i.id_customer = c.id_customer
                LEFT JOIN master_vessel v ON i.id_vessel = v.id_vessel
                LEFT JOIN master_bank b ON b.id_bank= i.id_bank                
                $where";
        $this->export($queryExport);
    }

    public function invoice($jenis_invoice = "") {
        $this->load->library("datagrid");

        $data = array();

        $this->log_event = "Membuka menu invoice persewaan";

        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("i.nomor_invoice", "c.nama_customer", "v.nama_vessel");
        $field_title = array("Nomor Invoice", "To", "Nama Vessel");
        $field_type = array("text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi_penyewaan/invoice", $field_name, $field_title, $field_type);
        if ($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(i.tanggal_invoice) BETWEEN '" . $data['srcPeriodStart'] . "' AND '" . $data['srcPeriodEnd'] . "' ";
        else
            $where = " WHERE TRUE ";

        if ($jenis_invoice != "") {
            $where .= " and i.is_final = " . $jenis_invoice;
        }

        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $offset = $this->input->get("per_page") ? $this->input->get("per_page") : 0;
        $length = 30;
        $result = $this->model_transaksi_penyewaan_invoice->getInvoiceData($where, $offset, $length);

        $this->datagrid->addMenu(GreyBox::createLink(base_url() . "index.php/transaksi_penyewaan/invoice_add/", "", "Tambah Data", "add", "onclick", 1024, 600));
        $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi_penyewaan/invoice_export/$jenis_invoice?" . $this->input->server("QUERY_STRING") . "\" class=\"report\" title=\"Export Data Invoice Order\">&nbsp;</a>");
        $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi_penyewaan/invoice/1?" . $this->input->server("QUERY_STRING") . "\">Lunas</a>/");
        $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi_penyewaan/invoice/0?" . $this->input->server("QUERY_STRING") . "\">Belum Lunas</a>/");
        $this->datagrid->addMenu("<a href=\"" . base_url() . "index.php/transaksi_penyewaan/invoice/?" . $this->input->server("QUERY_STRING") . "\">Semua</a>");

        $rowCount = $result->num_rows();

        $this->datagrid->setActionColumnsWidth(50);
        $this->datagrid->setColumns("No.", "Nomor Invoice", "Tanggal", "To", "Catatan", "Submitter");
        $this->datagrid->setPaginationDataNew($this->model_transaksi_penyewaan_invoice->get_scalar("SELECT COUNT(*) as jml FROM data_invoice_to_cust i $where", "jml"), $length, "transaksi_penyewaan/invoice", $rowCount, $offset);
        $this->datagrid->setButtonExportVisible(false);

        if ($rowCount > 0) {
            $nomor = $offset + 1;

            foreach ($result->result() as $row) {
                $rowID = $row->id_invoice;

                $this->datagrid->addRowAction("edit('" . $rowID . "')", "edit", "Ubah Invoice");
                $this->datagrid->addRowAction("cetak('" . $rowID . "')", "resume", "Cetak Invoice");
                $this->datagrid->addRowAction("hapus('" . $rowID . "')", "delete", "Hapus Invoice");
                if ($row->is_final == 0) {
                    $this->datagrid->addRowAction("finalisasi('" . $rowID . "')", "snapshot", "Finalisasi Invoice");
                    $this->datagrid->setRowStyle("GridItem2");
                } else {
                    $this->datagrid->setRowStyle("GridItem1");
                }
                $this->datagrid->addRowData(
                        $nomor++, $row->nomor_invoice, $row->tanggal_invoice, $row->nama_customer, $row->penerbit_invoice, $row->submitter
                );
            }
        } else {
            $this->datagrid->setEmptyDataState("Tidak ada data");
        }

        $data['breadcrumb'] = $this->breadCrumb(true);
        $data['date_picker'] = new jDatePicker();
        $data['filter_panel'] = $filter_panel;

        $this->loadMenu('transaksi_penyewaan/invoice', $data);
    }

    public function invoice_add($kode = "") {
        $data = array();

        if ($this->input->post("btnSubmit")) {
            $vars = array(
                "nomor_invoice" => "",
                "tanggal_invoice" => date("Y-m-d"),
                "id_perjanjian" => "",
                "tambahkan_ppn" => 0,
                "crc" => "IDR",
                "penerbit_invoice" => "",
                "btnSubmit" => "Save",
                "diskon_iv" => 0,
                "temp_id_iv" => 0,
                "id_item" => array(),
                "nama_item" => array(),
                "quantity" => array(),
                "harga_beli" => array(),
                "harga_jual" => array(),
                "harga_beli_dollar" => array(),
                "harga_jual_dollar" => array(),
                "using_dollar_currency" => 0,
                "satuan" => array()
            );

            retrieve_request($data, $vars);

            if ($data["temp_id_iv"] == 0)
                $data["temp_id_iv"] = $this->model_transaksi_penyewaan_invoice->nextInvoiceVal();

            $data["submitter"] = $this->userauth->getNik();
            $data["date_submit"] = date("Y-m-d H:i:s");
            $data["using_dollar_currency"] = $data["crc"] == "USD" ? 1 : 0;

            if ($data["id_perjanjian"] == "")
                $data["error"] = "Perjanjian can't be empty";
            else {
                if ($kode == "")
                    $id_invoice = $this->model_transaksi_penyewaan_invoice->insertInvoice($data);
                else {
                    $id_invoice = $kode;
                    $this->model_transaksi_penyewaan_invoice->updateInvoice($data, $id_invoice);
                }

                $this->model_transaksi_penyewaan_invoice->db->delete("data_invoice_to_cust_perjanjian_item", "id_invoice = '$id_invoice'");
                $i = 0;
                foreach ($data["id_item"] as $key) {
                    $varData = array(
                        "id_invoice" => $id_invoice,
                        "id_item" => $key,
                        "nama_item" => $data["nama_item"][$i],
                        "satuan_beli" => $data["satuan"][$i],
                        "quantity" => $data["quantity"][$i],
                        "harga_beli" => $data["harga_beli"][$i],
                        "harga_jual" => $data["harga_jual"][$i],
                        "harga_beli_dollar" => $data["harga_beli_dollar"][$i],
                        "harga_jual_dollar" => $data["harga_jual_dollar"][$i]
                    );
                    $this->model_transaksi_penyewaan_invoice->insertInvoiceItem($id_invoice, $varData);
                    $i++;
                }

                $data["is_success"] = 1;
                $data["kode"] = $id_invoice;
            }
        }

        if ($kode != "") {
            $id_po = $this->input->get("id_perjanjian", true);
            retrieve_invoice_data($data, $kode, $id_po);

            $data["kode"] = $kode;
            $data["temp_iv_id"] = $kode;
        } else {
            $id_po = $this->input->get("id_perjanjian", true);
            retrieve_perjanjian_data($data, $id_po);
            $data["diskon_iv"] = $data["diskon"];
            $data["tanggal_invoice"] = date("Y-m-d");
            $data["penerbit_invoice"] = $this->userauth->getNickName();

            $data["temp_iv_id"] = $this->model_transaksi_penyewaan_invoice->nextInvoiceVal();
        }

        $data['gbitemdollar'] = $this->greybox->createLink(base_url() . 'index.php/popup/item_finalisasi_dollar', '<span>Tambah Item</span>', 'Tambah Item', 'find', '', 1024, 450);
        $data["prefix"] = $this->model_transaksi_penyewaan_invoice->getPrefixInvoiceNo();
        $data['gbpo'] = $this->greybox->createLink(base_url() . 'index.php/transaksi_penyewaan/perjanjian/1', '<span></span>', 'Cari Data Perjanjian', 'find', '', 800, 480);

        $this->loadMenuHeaderPopup("transaksi_penyewaan/view_invoice_add", $data);
    }

    public function invoice_delete($kode) {
        $this->model_transaksi_penyewaan_invoice->deleteInvoice($kode);
        echo "<script>alert('Data berhasil dihapus');</script>";
        echo "<script>location.href = '" . site_url("transaksi_penyewaan/invoice?" . $_SERVER["QUERY_STRING"]) . "'</script>";
    }

    public function invoice_print($kode) {
        $data = array();
        retrieve_invoice_data($data, $kode);

        $this->load->library("dcpdf");

        $obj_pdf = new dcpdf('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $obj_pdf->SetCreator(PDF_CREATOR);
        $title = "Data Invoice";
        $obj_pdf->SetTitle($title);
        if ($data["use_header"]) {
            $obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
            $obj_pdf->setFooterVisible(TRUE);
        }
        $obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $obj_pdf->SetDefaultMonospacedFont('helvetica');
        $obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $obj_pdf->SetFont('times', '', 10);
        $obj_pdf->setFontSubsetting(false);
        $obj_pdf->AddPage();
        $content = $this->load->view("transaksi_penyewaan/view_invoice_print", $data, true);
        $obj_pdf->writeHTML($content, true, false, true, false, '');
        $obj_pdf->Output('invoice-' . $kode . '.pdf', 'I');
    }

    public function invoice_export($jenis_invoice = "") {
        $data['srcPeriodStart'] = $this->input->get_post('srcPeriodStart') != "" ? $this->input->get_post('srcPeriodStart') : date("Y-m-d");
        $data['srcPeriodEnd'] = $this->input->get_post('srcPeriodEnd') != "" ? $this->input->get_post('srcPeriodEnd') : date("Y-m-d");
        $data['srcPeriodMode'] = $this->input->get_post('srcPeriodMode') != "";

        $field_name = array("i.nomor_invoice", "c.nama_customer", "v.nama_vessel");
        $field_title = array("Nomor Invoice", "To", "Nama Vessel");
        $field_type = array("text", "text", "text");

        $filter_panel = new FilterPanel(base_url() . "transaksi_penyewaan/invoice", $field_name, $field_title, $field_type);
        if ($data['srcPeriodMode'] == 'include')
            $where = " WHERE date(i.tanggal_invoice) BETWEEN '" . $data['srcPeriodStart'] . "' AND '" . $data['srcPeriodEnd'] . "' ";
        else
            $where = " WHERE TRUE ";
        
        if ($jenis_invoice != ""){
            $where .= " and i.is_final = ".$jenis_invoice;
        }
        
        $filter = $filter_panel->getFilterString();
        $where .= $filter ? " AND $filter " : "";

        $queryExport = "SELECT i.nomor_invoice, i.tanggal_invoice, p.nomor_perjanjian, i.using_dollar_currency, i.tambahkan_ppn,
                i.penerbit_invoice, i.submitter, i.date_submit,
                c.nama_customer, c.kota_customer, c.alamat_customer, c.alamat_detail_customer, c.kode_pos_customer,
                c.telepon_customer, c.fax_customer, c.email_customer, c.attendance
                FROM data_invoice_to_cust_perjanjian i
                LEFT JOIN data_perjanjian p ON i.id_perjanjian = p.id_perjanjian
                LEFT JOIN master_customer c ON p.id_customer = c.id_customer
                $where";
        $this->export($queryExport);
    }

}

?>
